#include "lag.h"
#include "define.h"
#include "GameMap.h"
#include "Block.h"
#include "Hero.h"
#include "Enemy.h"
#include "Bullet.h"
#include "Bomb.h"
#include "Star.h"

// 项目结构
struct _stu_project
{
	int gameStatus = GAME_STATUS_RUN;					// 游戏状态
	bool refreshFlag = false;							// 刷新标识
	int level = 0;										// 游戏关卡
	int enemyMaxNum = 0;								// 敌方坦克最大数量
	int enemyCreateNum = 0;								// 敌方坦克投放数量
	int enemyDeadNum = 0;								// 敌方坦克死亡数量
	int enemyArmorDeadNum[4] = { 0,0,0,0 };				// 敌方不同装甲坦克死亡数量
	IMAGE imgLogo;										// Logo图片
	IMAGE imgLevel;										// 关卡图片
	IMAGE imgScore;										// 分数图片
	IMAGE imgSuccess;									// 游戏成功图片
	IMAGE imgFailure;									// 游戏失败图片
	int(*map)[26] = nullptr;							// 关卡地图

} stu_project;

// 子弹所在行列结构
struct _stu_bullet_pos
{
	int row1;
	int col1;
	int row2;
	int col2;
};

// 方块类
Block block;

// 我方坦克类
Hero hero(24, 8, TANK_DIRECTION_UP);

// 我方子弹池
vector<Bullet>& heroBulletPool = hero.getBulletPool();

// 敌方坦克类
vector<Enemy> enemyPool;

// 爆炸池
vector<Bomb> bombPool;

// 星星池
vector<Star> starPool;

// 函数声明
void createWindow();
void welcome();
void loadResources();
void initGame();
void paint();
void run();
void keyEvent();
void mouseEvent();
void starCreate();
void starAdd(int row, int column);
void enemyTankCreate(int row, int column);
void enemyTankMove();
void enemyTankShoot();
int enemyTankAI(Enemy& enemy);
void bombAdd(int x, int y);
void collide();
void doGame();
void newGame();
void showScore();
void getBulletPos(struct _stu_bullet_pos* pos, int x, int y, int direction);

// 坦克大战
int main()
{
	// 创建窗口
	createWindow();

	// 显示封面
	welcome();

	// 开始游戏
	newGame();

	// 暂停一下
	system("pause");

	// 关闭窗口
	closegraph();

	return 0;
}

// 创建窗口
void createWindow()
{
	// 创建并得到窗口句柄
	HWND hWnd = initgraph(WIN_WIDTH, WIN_HEIGHT);

	// 修改标题
	SetWindowText(hWnd, TITLE);

	// 居中显示
	myCenterWindow(hWnd);
}

// 加载资源
void loadResources()
{
	// 加载游戏成功图片
	loadimage(&stu_project.imgSuccess, "./resources/image/success.png");

	// 加载游戏失败图片
	loadimage(&stu_project.imgFailure, "./resources/image/failure.png");

	// 加载关卡图片
	loadimage(&stu_project.imgLevel, "./resources/image/level.png");

	// 加载Logo图片
	loadimage(&stu_project.imgLogo, "./resources/image/logo.png");

	// 加载分数图片
	loadimage(&stu_project.imgScore, "./resources/image/score.jpg");
}

// 显示封面
void welcome()
{
	// 显示封面
	IMAGE imgWelcome;
	loadimage(&imgWelcome, "./resources/image/welcome.gif");
	putimage(0, 0, &imgWelcome);

	// 加载资源
	loadResources();

	// 暂停一下
	system("pause");
}

// 初始化游戏
void initGame()
{
	// 项目参数初始化
	stu_project.gameStatus = GAME_STATUS_RUN;
	stu_project.refreshFlag = false;
	stu_project.enemyMaxNum = GameMap::getEnemyTankNum(stu_project.level);
	stu_project.enemyCreateNum = 0;
	stu_project.enemyDeadNum = 0;
	stu_project.map = GameMap::getMap();
	for (int i = 0; i < 4; i++) { stu_project.enemyArmorDeadNum[i] = 0; }

	// 设置游戏关卡
	GameMap::setLevel(stu_project.level);

	// 我方坦克初始化
	hero.reset();
	hero.status = TANK_STATUS_RUN;
	hero.toMap();

	// 敌方坦克池初始化10辆坦克
	int lenEnemyPool = enemyPool.size();
	if (lenEnemyPool == 0)
	{
		for (int i = 0; i < 10; i++)
		{
			Enemy enemy(0, 0, TANK_DIRECTION_DOWN);
			enemyPool.push_back(enemy);
		}
	}
	else
	{
		for (int i = 0; i < lenEnemyPool; i++)
		{
			enemyPool[i].reset();
			vector<Bullet>& enemyBulletPool = enemyPool[i].getBulletPool();
			int lenEnemyBulletPool = enemyBulletPool.size();
			for (int j = 0; j < lenEnemyBulletPool; j++) { enemyBulletPool[j].status = BULLET_STATUS_FREE; }
		}
	}

	// 星星初始化
	int lenStarPool = starPool.size();
	if (lenStarPool == 0)
	{
		for (int i = 0; i < 3; i++)
		{
			Star star;
			starPool.push_back(star);
		}
	}
	else
	{
		for (int i = 0; i < lenStarPool; i++) { starPool[i].status = STAR_STATUS_FREE; }
	}

	// 爆炸初始化
	int lenBombPool = bombPool.size();
	for (int i = 0; i < lenBombPool; i++) { bombPool[i].status = BOMB_STATUS_FREE; }

}

// 绘制窗口
void paint()
{
	// 开启双缓冲机制，防止闪烁
	BeginBatchDraw();

	// 绘制游戏区域
	setcolor(BLACK);
	cleardevice();
	setfillcolor(LIGHTGRAY);
	fillrectangle(GAME_WIDTH, -2, WIN_WIDTH, WIN_HEIGHT + 2);

	// 绘制分数
	settextstyle(20, 0, "微软雅黑");
	settextcolor(YELLOW);
	setbkmode(TRANSPARENT);
	myDrawString(GAME_WIDTH + 20, 6, "总数：" + to_string(stu_project.enemyMaxNum));
	myDrawString(GAME_WIDTH + 20, 26, "死亡：" + to_string(stu_project.enemyDeadNum));
	myDrawString(GAME_WIDTH + 20, 46, "剩余：" + to_string(stu_project.enemyMaxNum - stu_project.enemyDeadNum));
	int notCreateNum = stu_project.enemyMaxNum - stu_project.enemyCreateNum;
	if (notCreateNum > 0)
	{
		int logoRow = notCreateNum / 2;
		if (notCreateNum % 2 != 0) { logoRow++; }
		int logoCount = 0;
		for (int i = 0; i < logoRow; i++)
		{
			for (int j = 0; j < 2; j++)
			{
				if (logoCount >= notCreateNum) { break; }
				myDrawImage(GAME_WIDTH + 22 + j * (20 + 14), 80 + i * (16 + 4), &stu_project.imgLogo, WIN_WIDTH, WIN_HEIGHT);
				logoCount++;
			}
		}
	}
	myDrawImage(GAME_WIDTH + 20, 330, &stu_project.imgLevel);
	settextcolor(RED);
	myDrawString(GAME_WIDTH + 20, 380, "关数：" + to_string(stu_project.level + 1));
	settextcolor(WHITE);
	myDrawString(GAME_WIDTH + 20, 420, "作者：Lag");

	// 绘制地图
	block.draw();

	// 绘制我方坦克
	hero.draw();

	// 绘制我方子弹
	int lenHeroBulletPool = heroBulletPool.size();
	for (int i = 0; i < lenHeroBulletPool; i++)
	{
		if (heroBulletPool[i].status == BULLET_STATUS_RUN)
		{
			heroBulletPool[i].draw();
		}
	}

	// 绘制敌方坦克、子弹
	int lenEnemyPool = enemyPool.size();
	for (int i = 0; i < lenEnemyPool; i++)
	{
		if (enemyPool[i].status == TANK_STATUS_RUN) { enemyPool[i].draw(); }
		vector<Bullet>& enemyBulletPool = enemyPool[i].getBulletPool();
		int lenEnemyBulletPool = enemyBulletPool.size();
		for (int j = 0; j < lenEnemyBulletPool; j++)
		{
			if (enemyBulletPool[j].status == BULLET_STATUS_RUN) { enemyBulletPool[j].draw(); }
		}
	}

	// 绘制爆炸
	int lenBombPool = bombPool.size();
	for (int i = 0; i < lenBombPool; i++)
	{
		if (bombPool[i].status == BOMB_STATUS_RUN)
		{
			bombPool[i].draw();
		}
	}

	// 绘制星星
	int lenStarPool = starPool.size();
	for (int i = 0; i < lenStarPool; i++)
	{
		if (starPool[i].status == STAR_STATUS_RUN)
		{
			starPool[i].draw();
		}
	}

	// 结束双缓冲机制
	EndBatchDraw();
}

// 向星星池增加
void starAdd(int row, int column)
{
	// 流星雨
	myPlayAudio("./resources/audio/star.mp3");

	// 查找空闲的星星
	int len = starPool.size();
	for (int i = 0; i < len; i++)
	{
		if (starPool[i].status == STAR_STATUS_FREE)
		{
			starPool[i].row = row;
			starPool[i].column = column;
			starPool[i].frameIndex = 0;
			starPool[i].status = STAR_STATUS_RUN;
			break;
		}
	}
}

// 星星创建（在坦克创建前先创建星星）
void starCreate()
{
	// 创建坦克标识
	bool createFlag = false;

	if (stu_project.enemyCreateNum == 0 || myTimer(INTERVAL_CREATEENEMY, TIMERID_CREATEENEMY)) { createFlag = true; }

	if (createFlag)
	{
		// 判断投放地点是否为空
		int createPos[3] = { -1,-1,-1 };
		int createPosNum = 0;
		if (stu_project.map[0][0] == BLANK && stu_project.map[0][1] == BLANK && stu_project.map[1][0] == BLANK && stu_project.map[1][1] == BLANK)			// 判断左上角位置是否可以投放
		{
			createPos[createPosNum] = 0;
			createPosNum++;
		}
		if (stu_project.map[0][12] == BLANK && stu_project.map[0][13] == BLANK && stu_project.map[1][12] == BLANK && stu_project.map[1][13] == BLANK)		// 判断中间位置是否可以投放
		{
			createPos[createPosNum] = 12;
			createPosNum++;
		}
		if (stu_project.map[0][24] == BLANK && stu_project.map[0][25] == BLANK && stu_project.map[1][24] == BLANK && stu_project.map[1][25] == BLANK)		// 判断右上角位置是否可以投放
		{
			createPos[createPosNum] = 24;
			createPosNum++;
		}
		if (createPosNum < 1) { return; }		// 无投放位置，退出

		// 首次一次性投放3辆坦克
		if (stu_project.enemyCreateNum == 0)
		{
			for (int i = 0; i < createPosNum; i++)
			{
				// 先把茅坑占上
				stu_project.map[0][createPos[i]] = 999;
				stu_project.map[0][createPos[i] + 1] = 999;
				stu_project.map[1][createPos[i]] = 999;
				stu_project.map[1][createPos[i] + 1] = 999;
				// 增加星星
				starAdd(0, createPos[i]);
			}
		}
		else     // 每隔一段时间投放一辆坦克
		{
			// 判断是否达到最大投放数量
			if (stu_project.enemyCreateNum >= stu_project.enemyMaxNum) { return; }
			// 得到随机投放位置
			int pos = createPos[myRandom(0, createPosNum - 1)];
			// 先把茅坑占上
			stu_project.map[0][pos] = 999;
			stu_project.map[0][pos + 1] = 999;
			stu_project.map[1][pos] = 999;
			stu_project.map[1][pos + 1] = 999;
			// 增加星星
			starAdd(0, pos);
		}
	}
}

// 敌方坦克创建（在星星创建的位置）
void enemyTankCreate(int row, int column)
{
	// 在坦克池中寻找空闲的坦克
	Enemy* enemy = nullptr;
	int lenEnemyPool = enemyPool.size();
	for (int i = 0; i < lenEnemyPool; i++)
	{
		if (enemyPool[i].status == TANK_STATUS_FREE)
		{
			enemy = &enemyPool[i];
			break;
		}
	}
	if (enemy == nullptr)			// 没有就增加一个
	{
		Enemy newEnemy(0, 0, TANK_DIRECTION_DOWN);
		enemyPool.push_back(newEnemy);
		enemy = &enemyPool[lenEnemyPool];
	}

	// 开始投放
	enemy->row = row;
	enemy->oldRow = enemy->row;
	enemy->column = column;
	enemy->oldColumn = enemy->column;
	enemy->x = enemy->column * BLOCK_SIZE;
	enemy->y = 0;
	enemy->direction = TANK_DIRECTION_DOWN;
	if (stu_project.enemyCreateNum >= 3)
	{
		enemy->armor = myRandom(0, 3);
	}
	else
	{
		enemy->armor = 0;
	}
	enemy->originalArmor = enemy->armor;
	enemy->target = myRandom(TANK_OWNER_HERO, HOME);
	enemy->status = TANK_STATUS_RUN;
	enemy->toMap();
	stu_project.enemyCreateNum++;

}

// 敌方坦克AI（返回方向）
// 原理：判断目标与敌方坦克的相应位置，找出哪个方向最可能靠近目标。
int enemyTankAI(Enemy& enemy)
{
	// 先剔除墙与铁块那个方向（铁块暂时打不动）
	int validDirectory[4][2] = { -1,-1,-1,-1,-1,-1,-1,-1 };		// 可用方向数组[方向][空地/墙]
	int validDirectoryNum = 0;
	for (int i = 0; i < 4; i++)
	{
		bool blankFlag = false;		// 空地标识（true-是空地，false-非空地）
		if (i == TANK_DIRECTION_UP)
		{
			if (enemy.row == 0) { continue; }
			if (stu_project.map[enemy.row - 1][enemy.column] == IRON || stu_project.map[enemy.row - 1][enemy.column + 1] == IRON) { continue; }
			if (stu_project.map[enemy.row - 1][enemy.column] == BLANK && stu_project.map[enemy.row - 1][enemy.column + 1] == BLANK) { blankFlag = true; }
		}
		else if (i == TANK_DIRECTION_DOWN)
		{
			if (enemy.row == 24) { continue; }
			if (stu_project.map[enemy.row + 2][enemy.column] == IRON || stu_project.map[enemy.row + 2][enemy.column + 1] == IRON) { continue; }
			if (stu_project.map[enemy.row + 2][enemy.column] == BLANK && stu_project.map[enemy.row + 2][enemy.column + 1] == BLANK) { blankFlag = true; }
		}
		else if (i == TANK_DIRECTION_LEFT)
		{
			if (enemy.column == 0) { continue; }
			if (stu_project.map[enemy.row][enemy.column - 1] == IRON || stu_project.map[enemy.row + 1][enemy.column - 1] == IRON) { continue; }
			if (stu_project.map[enemy.row][enemy.column - 1] == BLANK && stu_project.map[enemy.row + 1][enemy.column - 1] == BLANK) { blankFlag = true; }
		}
		else if (i == TANK_DIRECTION_RIGHT)
		{
			if (enemy.column == 24) { continue; }
			if (stu_project.map[enemy.row][enemy.column + 2] == IRON || stu_project.map[enemy.row + 1][enemy.column + 2] == IRON) { continue; }
			if (stu_project.map[enemy.row][enemy.column + 2] == BLANK && stu_project.map[enemy.row + 1][enemy.column + 2] == BLANK) { blankFlag = true; }
		}
		validDirectory[validDirectoryNum][0] = i;
		if (blankFlag)
		{
			validDirectory[validDirectoryNum][1] = BLANK;
		}
		else
		{
			validDirectory[validDirectoryNum][1] = WALL;
		}
		validDirectoryNum++;
	}

	// 判断目标与敌方坦克位置关系
	int directory[4] = { -1,-1,-1,-1 };
	int targetRow;
	int targetColumn;
	if (enemy.target == TANK_OWNER_HERO)	// 目标是我方坦克
	{
		targetRow = hero.row;
		targetColumn = hero.column;
	}
	else   // 目标是老巢
	{
		targetRow = 24;
		targetColumn = 12;
	}
	if (targetColumn > enemy.column)		// 目标在敌方坦克右边
	{
		if (targetRow < enemy.row)			// 右上角（上或右）
		{
			for (int i = 0; i < validDirectoryNum; i++)
			{
				if (validDirectory[i][0] == TANK_DIRECTION_UP || validDirectory[i][0] == TANK_DIRECTION_RIGHT)
				{
					// 空地优先级别高
					if (validDirectory[i][1] == BLANK)
					{
						if (directory[0] != -1) { directory[1] = directory[0]; }
						directory[0] = validDirectory[i][0];
						continue;
					}
					// 从左向右填充
					for (int j = 0; j < 4; j++)
					{
						if (directory[j] == -1)
						{
							directory[j] = validDirectory[i][0];
							break;
						}
					}
				}
				else
				{
					// 从右向左填充
					for (int j = 3; j >= 0; j--)
					{
						if (directory[j] == -1)
						{
							directory[j] = validDirectory[i][0];
							break;
						}
					}
				}
			}
		}
		else     // 右下角（下或右）
		{
			for (int i = 0; i < validDirectoryNum; i++)
			{
				if (validDirectory[i][0] == TANK_DIRECTION_DOWN || validDirectory[i][0] == TANK_DIRECTION_RIGHT)
				{
					// 空地优先级别高
					if (validDirectory[i][1] == BLANK)
					{
						if (directory[0] != -1) { directory[1] = directory[0]; }
						directory[0] = validDirectory[i][0];
						continue;
					}
					// 从左向右填充
					for (int j = 0; j < 4; j++)
					{
						if (directory[j] == -1)
						{
							directory[j] = validDirectory[i][0];
							break;
						}
					}
				}
				else
				{
					// 从右向左填充
					for (int j = 3; j >= 0; j--)
					{
						if (directory[j] == -1)
						{
							directory[j] = validDirectory[i][0];
							break;
						}
					}
				}
			}
		}
		// 特殊情况（同一条线上）
		if (targetRow == enemy.row)
		{
			for (int i = 0; i < validDirectoryNum; i++)
			{
				if (validDirectory[i][0] == TANK_DIRECTION_RIGHT)
				{
					if (validDirectory[i][1] == BLANK) { return validDirectory[i][0]; }		// 是空地就必须勇敢的冲过去
				}
			}
		}
	}
	else									// 目标在敌方坦克左边
	{
		if (targetRow < enemy.row)			// 左上角（上或左）
		{
			for (int i = 0; i < validDirectoryNum; i++)
			{
				if (validDirectory[i][0] == TANK_DIRECTION_UP || validDirectory[i][0] == TANK_DIRECTION_LEFT)
				{
					// 空地优先级别高
					if (validDirectory[i][1] == BLANK)
					{
						if (directory[0] != -1) { directory[1] = directory[0]; }
						directory[0] = validDirectory[i][0];
						continue;
					}
					// 从左向右填充
					for (int j = 0; j < 4; j++)
					{
						if (directory[j] == -1)
						{
							directory[j] = validDirectory[i][0];
							break;
						}
					}
				}
				else
				{
					// 从右向左填充
					for (int j = 3; j >= 0; j--)
					{
						if (directory[j] == -1)
						{
							directory[j] = validDirectory[i][0];
							break;
						}
					}
				}
			}
		}
		else     // 左下角（下或左）
		{
			for (int i = 0; i < validDirectoryNum; i++)
			{
				if (validDirectory[i][0] == TANK_DIRECTION_DOWN || validDirectory[i][0] == TANK_DIRECTION_LEFT)
				{
					// 空地优先级别高
					if (validDirectory[i][1] == BLANK)
					{
						if (directory[0] != -1) { directory[1] = directory[0]; }
						directory[0] = validDirectory[i][0];
						continue;
					}
					// 从左向右填充
					for (int j = 0; j < 4; j++)
					{
						if (directory[j] == -1)
						{
							directory[j] = validDirectory[i][0];
							break;
						}
					}
				}
				else
				{
					// 从右向左填充
					for (int j = 3; j >= 0; j--)
					{
						if (directory[j] == -1)
						{
							directory[j] = validDirectory[i][0];
							break;
						}
					}
				}
			}
		}
		// 特殊情况（同一条线上）
		if (targetRow == enemy.row)
		{
			for (int i = 0; i < validDirectoryNum; i++)
			{
				if (validDirectory[i][0] == TANK_DIRECTION_LEFT)
				{
					if (validDirectory[i][1] == BLANK) { return validDirectory[i][0]; }		// 是空地就必须勇敢的冲过去
				}
			}
		}
	}

	if (targetColumn == enemy.column)	// 目标在敌方坦克正上或下方
	{
		// 特殊情况（同一条线上）
		if (targetRow < enemy.row)		// 正上方
		{
			for (int i = 0; i < validDirectoryNum; i++)
			{
				if (validDirectory[i][0] == TANK_DIRECTION_UP)
				{
					if (validDirectory[i][1] == BLANK) { return validDirectory[i][0]; }		// 是空地就必须勇敢的冲过去
				}
			}
		}
		else
		{
			for (int i = 0; i < validDirectoryNum; i++)
			{
				if (validDirectory[i][0] == TANK_DIRECTION_DOWN)
				{
					if (validDirectory[i][1] == BLANK) { return validDirectory[i][0]; }		// 是空地就必须勇敢的冲过去
				}
			}
		}
	}

	// 方向补全
	for (int i = 0; i < 4; i++)
	{
		if (directory[i] == -1) { directory[i] = enemy.direction; }
	}

	// 随机抽取4:3:2:1
	int random = myRandom(1, 10);
	if (random <= 4)
	{
		return directory[0];
	}
	else if (random <= 7)
	{
		return directory[1];
	}
	else if (random <= 9)
	{
		return directory[2];
	}
	else
	{
		return directory[3];
	}

}

// 敌方坦克移动
void enemyTankMove()
{
	if (myTimer(INTERVAL_MOVEENEMY, TIMERID_MOVEENEMY))
	{
		int lenEnemyPool = enemyPool.size();
		for (int i = 0; i < lenEnemyPool; i++)
		{
			if (enemyPool[i].status == TANK_STATUS_RUN)
			{
				// 得到移动方向
				enemyPool[i].direction = enemyTankAI(enemyPool[i]);
				enemyPool[i].move(enemyPool[i].direction);
				stu_project.refreshFlag = true;
			}
		}
	}
}

// 敌方坦克射击
void enemyTankShoot()
{
	if (myTimer(INTERVAL_BULLET_SHOOT, TIMERID_BULLET_SHOOT))
	{
		int lenEnemyPool = enemyPool.size();
		for (int i = 0; i < lenEnemyPool; i++)
		{
			if (enemyPool[i].status == TANK_STATUS_RUN)
			{
				// 敌方坦克比较傻，不爱射击
				if (myRandom(1, 10) < 4) { enemyPool[i].shoot(); }			// 30%几率开枪
				stu_project.refreshFlag = true;
			}
		}
	}
}

// 向爆炸池增加
void bombAdd(int x, int y)
{
	// 查找空闲的爆炸
	Bomb* bomb = nullptr;
	int len = bombPool.size();
	for (int i = 0; i < len; i++)
	{
		if (bombPool[i].status == BOMB_STATUS_FREE)
		{
			bomb = &bombPool[i];
			break;
		}
	}
	if (bomb == nullptr)				// 没有就增加一个
	{
		Bomb newBomb;
		bombPool.push_back(newBomb);
		bomb = &bombPool[len];
	}
	bomb->x = x;
	bomb->y = y;
	bomb->frameIndex = 0;
	bomb->status = BOMB_STATUS_RUN;
}

// 得到子弹所在行列位置（子弹位于坦克中间位置，所以正对着2个格子的中间位置，所以计算时2个格子都在其射击范围内）
void getBulletPos(struct _stu_bullet_pos* pBulletPos, int x, int y, int direction)
{
	int x1, y1, x2, y2;

	// 重算子弹图片中心点坐标（因为此时的x与y是子弹图片左上角的坐标）
	x = x + BULLET_SIZE / 2;
	y = y + BULLET_SIZE / 2;

	// 根据方向判断2个格子位置
	if (direction == TANK_DIRECTION_UP || direction == TANK_DIRECTION_DOWN)
	{
		x1 = x - BLOCK_SIZE / 2;
		y1 = y;
		x2 = x + BLOCK_SIZE / 2;
		y2 = y;
	}
	else
	{
		x1 = x;
		y1 = y - BLOCK_SIZE / 2;
		x2 = x;
		y2 = y + BLOCK_SIZE / 2;
	}
	pBulletPos->row1 = y1 / BLOCK_SIZE;
	pBulletPos->col1 = x1 / BLOCK_SIZE;
	pBulletPos->row2 = y2 / BLOCK_SIZE;
	pBulletPos->col2 = x2 / BLOCK_SIZE;
}

// 碰撞处理
void collide()
{
	// 子弹所在位置结构体
	struct _stu_bullet_pos stu_bullet_pos;

	// 判断我方子弹是否与敌方坦克或块或老巢碰撞
	int lenHeroBulletPool = heroBulletPool.size();
	for (int i = 0; i < lenHeroBulletPool; i++)
	{
		if (heroBulletPool[i].status == BULLET_STATUS_RUN)
		{
			// 得到子弹所在行与列
			getBulletPos(&stu_bullet_pos, heroBulletPool[i].x, heroBulletPool[i].y, heroBulletPool[i].direction);
			// 得到子弹2个点的值
			int v1 = stu_project.map[stu_bullet_pos.row1][stu_bullet_pos.col1];
			int v2 = stu_project.map[stu_bullet_pos.row2][stu_bullet_pos.col2];
			if (v1 == 0 && v2 == 0) { continue; }
			if (v1 == TANK_OWNER_HERO && v2 == TANK_OWNER_HERO) { continue; }
			// 判断是否与墙块碰撞
			if (v1 == WALL) { stu_project.map[stu_bullet_pos.row1][stu_bullet_pos.col1] = 0; }
			if (v2 == WALL) { stu_project.map[stu_bullet_pos.row2][stu_bullet_pos.col2] = 0; }
			// 判断是否与老巢碰撞
			if (v1 == HOME || v2 == HOME) { stu_project.gameStatus = GAME_STATUS_OVER; }
			// 判断是否与敌方坦克碰撞
			int lenEnemyPool = enemyPool.size();
			for (int i = 0; i < lenEnemyPool; i++)
			{
				if (enemyPool[i].status == TANK_STATUS_RUN)
				{
					if (
						(enemyPool[i].row == stu_bullet_pos.row1 && enemyPool[i].column == stu_bullet_pos.col1) ||
						(enemyPool[i].row == stu_bullet_pos.row1 && enemyPool[i].column + 1 == stu_bullet_pos.col1) ||
						(enemyPool[i].row + 1 == stu_bullet_pos.row1 && enemyPool[i].column == stu_bullet_pos.col1) ||
						(enemyPool[i].row + 1 == stu_bullet_pos.row1 && enemyPool[i].column + 1 == stu_bullet_pos.col1) ||
						(enemyPool[i].row == stu_bullet_pos.row2 && enemyPool[i].column == stu_bullet_pos.col2) ||
						(enemyPool[i].row == stu_bullet_pos.row2 && enemyPool[i].column + 1 == stu_bullet_pos.col2) ||
						(enemyPool[i].row + 1 == stu_bullet_pos.row2 && enemyPool[i].column == stu_bullet_pos.col2) ||
						(enemyPool[i].row + 1 == stu_bullet_pos.row2 && enemyPool[i].column + 1 == stu_bullet_pos.col2)
						)
					{
						myPlayAudio("./resources/audio/boom.wav");
						if (enemyPool[i].armor == 0)
						{
							enemyPool[i].reset();
							stu_project.enemyDeadNum++;
							stu_project.enemyArmorDeadNum[enemyPool[i].originalArmor]++;
							if (stu_project.enemyDeadNum >= stu_project.enemyMaxNum) { stu_project.gameStatus = GAME_STATUS_WIN; }
							break;
						}
						else
						{
							enemyPool[i].armor--;
						}
					}
				}
			}
			// 子弹销毁
			heroBulletPool[i].status = BULLET_STATUS_FREE;
			// 子弹爆炸
			bombAdd(heroBulletPool[i].x, heroBulletPool[i].y);
		}
	}

	// 判断敌方子弹是否与我方坦克或块或老巢碰撞（不需要判断敌方坦克状态，因为即使坦克销毁子弹可能仍然在飞）
	int lenEnemyPool = enemyPool.size();
	for (int m = 0; m < lenEnemyPool; m++)
	{
		vector<Bullet>& enemyBulletPool = enemyPool[m].getBulletPool();
		int lenEnemyBulletPool = enemyBulletPool.size();
		for (int i = 0; i < lenEnemyBulletPool; i++)
		{
			if (enemyBulletPool[i].status == BULLET_STATUS_RUN)
			{
				// 得到子弹所在行与列
				getBulletPos(&stu_bullet_pos, enemyBulletPool[i].x, enemyBulletPool[i].y, enemyBulletPool[i].direction);
				// 得到子弹2个点的值
				int v1 = stu_project.map[stu_bullet_pos.row1][stu_bullet_pos.col1];
				int v2 = stu_project.map[stu_bullet_pos.row2][stu_bullet_pos.col2];
				if (v1 == 0 && v2 == 0) { continue; }
				if (v1 == TANK_OWNER_ENEMY && v2 == TANK_OWNER_ENEMY) { continue; }
				// 判断是否与墙块碰撞
				if (v1 == WALL) { stu_project.map[stu_bullet_pos.row1][stu_bullet_pos.col1] = 0; }
				if (v2 == WALL) { stu_project.map[stu_bullet_pos.row2][stu_bullet_pos.col2] = 0; }
				// 判断是否与老巢碰撞
				if (v1 == HOME || v2 == HOME) { stu_project.gameStatus = GAME_STATUS_OVER; }
				// 判断是否与我方坦克碰撞
				if (hero.status == TANK_STATUS_RUN)
				{
					if (
						(hero.row == stu_bullet_pos.row1 && hero.column == stu_bullet_pos.col1) ||
						(hero.row == stu_bullet_pos.row1 && hero.column + 1 == stu_bullet_pos.col1) ||
						(hero.row + 1 == stu_bullet_pos.row1 && hero.column == stu_bullet_pos.col1) ||
						(hero.row + 1 == stu_bullet_pos.row1 && hero.column + 1 == stu_bullet_pos.col1) ||
						(hero.row == stu_bullet_pos.row2 && hero.column == stu_bullet_pos.col2) ||
						(hero.row == stu_bullet_pos.row2 && hero.column + 1 == stu_bullet_pos.col2) ||
						(hero.row + 1 == stu_bullet_pos.row2 && hero.column == stu_bullet_pos.col2) ||
						(hero.row + 1 == stu_bullet_pos.row2 && hero.column + 1 == stu_bullet_pos.col2)
						)
					{
						if (hero.armor == 0)
						{
							hero.reset();
							stu_project.gameStatus = GAME_STATUS_OVER;
						}
						else
						{
							hero.armor--;
						}
					}
				}
				// 子弹销毁
				enemyBulletPool[i].status = BULLET_STATUS_FREE;
				// 子弹爆炸
				bombAdd(enemyBulletPool[i].x, enemyBulletPool[i].y);
			}
		}
	}

}

// 游戏进程
void run()
{
	// 重置刷新标识
	stu_project.refreshFlag = false;

	// 星星创建
	starCreate();

	// 星星进程
	if (myTimer(INTERVAL_STAR, TIMERID_STAR))
	{
		int len = starPool.size();
		for (int i = 0; i < len; i++)
		{
			if (starPool[i].status == STAR_STATUS_RUN)
			{
				int index = starPool[i].frameIndex;
				if (index >= starPool[i].maxFrame - 1)
				{
					starPool[i].status = STAR_STATUS_FREE;
					enemyTankCreate(starPool[i].row, starPool[i].column);		// 创建敌方坦克
					continue;
				}
				starPool[i].frameIndex = ++index;
			}
		}
	}

	// 敌方坦克移动
	enemyTankMove();

	// 敌方坦克射击
	enemyTankShoot();

	// 坦克移动进程
	if (myTimer(INTERVAL_TANKMOVE, TIMERID_TANKMOVE))
	{
		// 我方坦克移动
		if (hero.oldRow != hero.row)
		{
			int destY = hero.row * BLOCK_SIZE;
			if (hero.direction == TANK_DIRECTION_UP)
			{
				if (hero.y > destY)
				{
					hero.y = hero.y - hero.speed;
					hero.track = !hero.track;		// 切换履带
				}
				else
				{
					hero.oldRow = hero.row;
					hero.y = destY;					// 坐标微调
				}
			}
			else if (hero.direction == TANK_DIRECTION_DOWN)
			{
				if (hero.y < destY)
				{
					hero.y = hero.y + hero.speed;
					hero.track = !hero.track;
				}
				else
				{
					hero.oldRow = hero.row;
					hero.y = destY;
				}
			}
			stu_project.refreshFlag = true;
		}
		else if (hero.column != hero.oldColumn)
		{
			int destX = hero.column * BLOCK_SIZE;
			if (hero.direction == TANK_DIRECTION_LEFT)
			{
				if (hero.x > destX)
				{
					hero.x = hero.x - hero.speed;
					hero.track = !hero.track;
				}
				else
				{
					hero.oldColumn = hero.column;
					hero.x = destX;
				}
			}
			else if (hero.direction == TANK_DIRECTION_RIGHT)
			{
				if (hero.x < destX)
				{
					hero.x = hero.x + hero.speed;
					hero.track = !hero.track;
				}
				else
				{
					hero.oldColumn = hero.column;
					hero.x = destX;
				}
			}
			stu_project.refreshFlag = true;
		}
		// 敌方坦克移动
		int lenEnemyPool = enemyPool.size();
		for (int i = 0; i < lenEnemyPool; i++)
		{
			if (enemyPool[i].status == TANK_STATUS_RUN)
			{
				if (enemyPool[i].oldRow != enemyPool[i].row)
				{
					int destY = enemyPool[i].row * BLOCK_SIZE;
					if (enemyPool[i].direction == TANK_DIRECTION_UP)
					{
						if (enemyPool[i].y > destY)
						{
							enemyPool[i].y = enemyPool[i].y - enemyPool[i].speed;
							enemyPool[i].track = !enemyPool[i].track;		// 切换履带
						}
						else
						{
							enemyPool[i].oldRow = enemyPool[i].row;
							enemyPool[i].y = destY;					// 坐标微调
						}
					}
					else if (enemyPool[i].direction == TANK_DIRECTION_DOWN)
					{
						if (enemyPool[i].y < destY)
						{
							enemyPool[i].y = enemyPool[i].y + enemyPool[i].speed;
							enemyPool[i].track = !enemyPool[i].track;
						}
						else
						{
							enemyPool[i].oldRow = enemyPool[i].row;
							enemyPool[i].y = destY;
						}
					}
					stu_project.refreshFlag = true;
				}
				else if (enemyPool[i].column != enemyPool[i].oldColumn)
				{
					int destX = enemyPool[i].column * BLOCK_SIZE;
					if (enemyPool[i].direction == TANK_DIRECTION_LEFT)
					{
						if (enemyPool[i].x > destX)
						{
							enemyPool[i].x = enemyPool[i].x - enemyPool[i].speed;
							enemyPool[i].track = !enemyPool[i].track;
						}
						else
						{
							enemyPool[i].oldColumn = enemyPool[i].column;
							enemyPool[i].x = destX;
						}
					}
					else if (enemyPool[i].direction == TANK_DIRECTION_RIGHT)
					{
						if (enemyPool[i].x < destX)
						{
							enemyPool[i].x = enemyPool[i].x + enemyPool[i].speed;
							enemyPool[i].track = !enemyPool[i].track;
						}
						else
						{
							enemyPool[i].oldColumn = enemyPool[i].column;
							enemyPool[i].x = destX;
						}
					}
					stu_project.refreshFlag = true;
				}
			}
		}
	}

	// 子弹进程
	if (myTimer(INTERVAL_BULLET_RUN, TIMERID_BULLET_RUN))
	{
		// 我方子弹运行
		int lenHeroBulletPool = heroBulletPool.size();
		for (int i = 0; i < lenHeroBulletPool; i++)
		{
			if (heroBulletPool[i].status == BULLET_STATUS_RUN)
			{
				heroBulletPool[i].run();
			}
		}
		// 敌方子弹运行
		int lenEnemyPool = enemyPool.size();
		for (int i = 0; i < lenEnemyPool; i++)
		{
			vector<Bullet>& enemyBulletPool = enemyPool[i].getBulletPool();
			int lenEnemyBulletPool = enemyBulletPool.size();
			for (int j = 0; j < lenEnemyBulletPool; j++)
			{
				if (enemyBulletPool[j].status == BULLET_STATUS_RUN)
				{
					enemyBulletPool[j].run();
				}
			}
		}
	}

	// 碰撞处理
	collide();

	// 爆炸进程
	if (myTimer(INTERVAL_BOMB, TIMERID_BOMB))
	{
		int len = bombPool.size();
		for (int i = 0; i < len; i++)
		{
			if (bombPool[i].status == BOMB_STATUS_RUN)
			{
				int index = bombPool[i].frameIndex;
				if (index >= bombPool[i].maxFrame - 1)
				{
					bombPool[i].status = BOMB_STATUS_FREE;
					break;
				}
				bombPool[i].frameIndex = ++index;
			}
		}
	}

	// 刷新界面
	if (stu_project.refreshFlag) { paint(); }

}

// 键盘监控
void keyEvent()
{
	// 重置刷新标识
	stu_project.refreshFlag = false;

	// 方向键只运行同时按一个，用else if判断
	if (myKeyDown(VK_UP))				// 上键
	{
		if (hero.move(TANK_DIRECTION_UP)) { stu_project.refreshFlag = true; }
	}
	else if (myKeyDown(VK_DOWN))		// 下键
	{
		if (hero.move(TANK_DIRECTION_DOWN)) { stu_project.refreshFlag = true; }
	}
	else if (myKeyDown(VK_LEFT))		// 左键
	{
		if (hero.move(TANK_DIRECTION_LEFT)) { stu_project.refreshFlag = true; }
	}
	else if (myKeyDown(VK_RIGHT))		// 右键
	{
		if (hero.move(TANK_DIRECTION_RIGHT)) { stu_project.refreshFlag = true; }
	}

	// 其他键不受限制
	if (myKeyDown(VK_SPACE))			// 空格
	{
		hero.shoot();
		stu_project.refreshFlag = true;
	}

	// 刷新界面
	if (stu_project.refreshFlag) { paint(); }
}

// 鼠标监控
void mouseEvent()
{
	ExMessage msg;							// 鼠标消息结构体
	if (peekmessage(&msg, EM_MOUSE))		// 只监听鼠标消息
	{
		switch (msg.message)
		{
		case WM_LBUTTONUP:				// 鼠标左键释放（用msg.x与msg.y来判断点击位置）
			break;
		case WM_MOUSEMOVE:				// 鼠标移动
			break;
		case WM_RBUTTONUP:				// 鼠标右键释放
			break;
		}
	}
}

// 显示本关分数
void showScore()
{
	putimage(0, 0, &stu_project.imgScore);
	settextstyle(24, 0, "微软雅黑");
	settextcolor(YELLOW);
	setbkmode(TRANSPARENT);
	myDrawString(330, 58, to_string(stu_project.level + 1));
	settextcolor(WHITE);
	int score = 0;
	for (int i = 0; i < 4; i++)
	{
		score = score + stu_project.enemyArmorDeadNum[i] * 100 * (i + 1);
		myDrawString(176, 183 + i * 42, to_string(stu_project.enemyArmorDeadNum[i]));
		myDrawString(220, 183 + i * 42, "×");
		myDrawString(260, 183 + i * 42, to_string(100 * (i + 1)));
		myDrawString(320, 183 + i * 42, "=");
		myDrawString(350, 183 + i * 42, to_string(stu_project.enemyArmorDeadNum[i] * 100 * (i + 1)));
		Sleep(500);
	}
	settextcolor(RED);
	myDrawString(350, 350, to_string(score));
	Sleep(500);
	system("pause");
}

// 处理游戏状态（下一关或失败）
void doGame()
{
	// 游戏结束
	if (stu_project.gameStatus == GAME_STATUS_OVER)
	{
		myPlayAudio("./resources/audio/over.mp3");
		myDrawImage((GAME_WIDTH - stu_project.imgFailure.getwidth()) / 2, (GAME_HEIGHT - stu_project.imgFailure.getheight()) / 2, &stu_project.imgFailure);
		Sleep(1000);
		showScore();
	}
	else if (stu_project.gameStatus == GAME_STATUS_WIN)
	{
		myDrawImage((GAME_WIDTH - stu_project.imgSuccess.getwidth()) / 2, (GAME_HEIGHT - stu_project.imgSuccess.getheight()) / 2, &stu_project.imgSuccess);
		Sleep(1000);
		showScore();
		stu_project.level++;
		if (stu_project.level < GameMap::getMaxLevel())
		{
			newGame();
		}
	}

}

// 开始游戏
void newGame()
{
	myPlayAudio("./resources/audio/begin.mp3");

	// 初始化游戏
	initGame();

	// 开始游戏
	while (stu_project.gameStatus == GAME_STATUS_RUN)
	{
		// 开始刷新
		if (myTimer(INTERVAL_REFRESH, TIMERID_REFRESH))
		{
			// 绘制窗口
			paint();

			// 游戏进程
			run();
		}

		// 键盘监控
		keyEvent();

		// 鼠标监控（必须随时监控，否则不湿滑）
		//mouseEvent();
	}

	// 处理游戏状态（下一关或失败）
	doGame();
}